package cc.magicjson.p6spy.service;

import cc.magicjson.p6spy.entity.User;
import cc.magicjson.p6spy.bo.UserBO;
import cc.magicjson.p6spy.repository.UserRepository;
import cc.magicjson.p6spy.mapper.UserMapper;
import cc.magicjson.p6spy.utils.MapstructUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final UserMapper userMapper;

    @Transactional(readOnly = true)
    public List<UserBO> getAllUsers() {
        List<User> users = userRepository.findAll();
        return users.stream()
                .map(user -> MapstructUtils.convert(user,UserBO.class))
                .collect(Collectors.toList());
    }

    @Transactional
    public UserBO createUser(UserBO userBO) {
        User user = MapstructUtils.convert(userBO, User.class);
        User savedUser = userRepository.save(user);
        return MapstructUtils.convert(savedUser, UserBO.class);
    }

    @Transactional(readOnly = true)
    public UserBO getUserById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
        return MapstructUtils.convert(user, UserBO.class);
    }

    @Transactional
    public void simulateSlowQuery() {
        try {
            Thread.sleep(2000); // Simulate a slow operation
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        // Execute a query after the delay
        List<User> users = userRepository.findAll();
        System.out.println("Found " + users.size() + " users");
    }
}
